//
//  PolygonView.m
//  HelloPoly
//
//  Created by mstevens on 10/15/09.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "PolygonView.h"


@implementation PolygonView

@synthesize shapeName;

- (id)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
    }
    return self;
}


- (void)drawRect:(CGRect)rect { 
	int theNumber = [poly.shape numberOfSides];
	
	NSArray *points = [self pointsForPolygonInRect:rect	numberOfSides:theNumber];
	CGContextRef context = UIGraphicsGetCurrentContext(); 
	CGContextBeginPath (context);
	BOOL first = YES;
	for (NSValue *point in points) {
		CGPoint thePoint =[point CGPointValue];
		// NSLog(@"Point: %f,%f",  thePoint.x, thePoint.y);
		if (first) {
			CGContextMoveToPoint(context, thePoint.x, thePoint.y);
			first = NO;
		} else {
			CGContextAddLineToPoint(context, thePoint.x, thePoint.y);
		}
	}

	CGContextClosePath (context); 
	[[UIColor redColor] setStroke]; 
	CGContextDrawPath (context, kCGPathStroke);
	
	[shapeName setText:[poly.shape name]];
}

- (NSArray *)pointsForPolygonInRect:(CGRect)rect numberOfSides:(int)numberOfSides { 
	CGPoint center = CGPointMake(rect.size.width / 2.0, rect.size.height / 2.7); 
	float radius = 0.7 * center.x; 
	NSMutableArray *result = [NSMutableArray array]; 
	float angle = (2.0 * M_PI) / numberOfSides; 
	float exteriorAngle = M_PI - angle; 
	float rotationDelta = angle - (0.5 * exteriorAngle); 
	
	for (int currentAngle = 0; currentAngle < numberOfSides; currentAngle++) { 
		float newAngle = (angle * currentAngle) - rotationDelta; 
		float curX = cos(newAngle) * radius; 
		float curY = sin(newAngle) * radius; 
		[result addObject:[NSValue valueWithCGPoint:CGPointMake(center.x + curX, 
																center.y + curY)]]; 
	} 
	return result; 
}



- (void)dealloc {
	[poly release];
	[shapeName release];
    [super dealloc];
}


@end
